<template>
  <div class="colunmDetail">
    <div class="colunmDetail-header">

      <a-button type="primary" :disabled="!channelPermDto.channelMergePerm" class="createStaticPage"
        @click="mergeRecords()">合并栏目</a-button>
      <a-button class="previewSite" :disabled="!channelPermDto.staticPagePerm" v-if="0">生成栏目静态页</a-button>
      <a-button class="previewSite" :disabled="!detailData.previewAddress" @click="goToChannelPreview">预览栏目</a-button>

      <a-button class="previewSite" :type="isBasicSetting ? 'primary' : ''" @click="changeBasic(true)">基础设置</a-button>
      <a-button class="previewSite" :type="!isBasicSetting ? 'primary' : ''" @click="changeBasic(false)"
        v-if="detailData.leafNodeFlag">采集设置</a-button>
      <a-popconfirm placement="bottomRight" :disabled="!channelPermDto.recycledPerm"
        :ok-text="record.children && record.children.length ? '我知道了' : '确认'" cancel-text="取消" @confirm="confirmDelete()">
        <template #title>
          <p style="width: 197px">
            {{ deleteTips }}
          </p>
        </template>
        <a-button class="deleteSite" :disabled="!channelPermDto.recycledPerm" @click="deleteRecords()">移入回收站</a-button>
      </a-popconfirm>
    </div>
    <div class="now-colunm">
      <span>当前栏目：</span>
      <span>{{ channelName }}</span>
    </div>
    <transfer :isVisible="tranfer_isVisible" :modelId="modelId" @handleOk="handleOk"
      @handleCancle="tranfer_isVisible = false" :channelName="channelName"></transfer>
    <div v-if="isBasicSetting" class="columnInfoDetail">
      <a-tabs v-model:activeKey="editActiveKey">
        <a-tab-pane key="1" tab="基本设置">
        </a-tab-pane>
        <a-tab-pane key="2" tab="扩展设置">
        </a-tab-pane>
        <a-tab-pane key="3" tab="seo设置">
        </a-tab-pane>
      </a-tabs>
      <div v-show="editActiveKey == '1'" class="columnSettings">
        <a-form-item name="columnModel" label="栏目模型" :rules="[rule]"
          :style="{ marginLeft: 137 + 'px', marginTop: 24 + 'px' }">
          <div class="text">
            {{ modelName }}
          </div>
        </a-form-item>
        <baseInfo :basicFormState="basicFormState" :isVisibleObj="isVisibleObj" :addModelSelection="addModelSelection"
          :contentModelList="contentModelList" ref="basic"></baseInfo>
      </div>
      <div v-show="editActiveKey == '2'" class="columnSettings">
        <extendConfig :extFormState="extFormState" :isVisibleObj="isVisibleObj" :addModelSelection="addModelSelection"
          :contentModelList="contentModelList" ref="ext"></extendConfig>
      </div>
      <div v-show="editActiveKey == '3'" class="columnSettings">
        <seoInfo :seoFormState="seoFormState" :isVisibleObj="isVisibleObj" :addModelSelection="addModelSelection"
          :contentModelList="contentModelList" ref="seo"></seoInfo>
      </div>
    </div>
    <div v-if="!isBasicSetting" class="colletion">
      <collection v-show="isShowCollect" :collectionState="collectionState" :channelId="route.query.channelId"
        ref="collect">
      </collection>
    </div>
    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="!channelPermDto.editPerm" @click="saveData">保存</a-button>
    </div>
    <base-modal :width="modalProps.width" :isVisible="isVisibleObj.isVisible" :title="modalProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="handleCancle" class="addMember_modal">
      <template v-slot:body>
        <div class="modal_table">
          <!-- 添加成员表格展示部分 -->
          <a-button type="primary" class="rebackSite" @click="rebackConfig">一键恢复站点配置</a-button>
          <div class="baseTable">
            <baseTable :columns="columns.addColumnModelColumns" :selectedRowKeys="rowSelectedKey" :hideSelectAll="1"
              :dataSource="contentModelList" :scroll="{ y: 200 }" ref="addModelBaseTables">
              <template #headerCell="{column}">
                <template v-if="column.key === 'tplPc'">
                  <div class="tpllPc">
                  <span class="title">{{ column.title }}</span>
              <a-tooltip placement="right">
                <template #title>
                  <span>内容模型绑定内容模板后可进行选择</span>
                </template>
                <span style="color: #1c6bec;" class="iconfont icon-hint"></span>
              </a-tooltip>
                <span class="tips">内容模型绑定内容模板后可进行选择</span>
                </div>
                </template>
                <template v-if="column.key === 'tplMobile'">
                  <div class="tpllPc">
                  <span class="title">{{ column.title }}</span>
              <a-tooltip placement="right">
                <template #title>
                  <span>内容模型绑定内容模板后可进行选择</span>
                </template>
                <span style="color: #1c6bec;" class="iconfont icon-hint"></span>
              </a-tooltip>
                <span class="tips">内容模型绑定内容模板后可进行选择</span>
                </div>
                </template>
              </template>
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.ellipsis">
                  <table-tool-tip :text="text" :column="column"></table-tool-tip>
                </template>
                <template v-if="column.dataIndex === 'tplPc'">
                  <a-select class="modal-select" v-model:value="record.tplPc" @focus="onFocus(record.id, 1)"
                    placeholder="请选择" :options="pcTplList"></a-select>
                </template>
              </template>
            </baseTable>
          </div>
        </div>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, computed, createVNode, nextTick } from "vue";
import { comps, configSetting } from "@/components/draggable/exportComp";
import baseTable from "@/components/table/baseTable.vue";
import { dataSourceType, detailDataItemType } from "@/type.d";
import request from "@/api/index";
import columns from "@/components/table/tableConfig/columnsName";
import tableToolTip from "@/components/table/tableToolTip.vue";
import baseInfo from "./from/baseInfo.vue";
import extendConfig from "./from/extendConfig.vue";
import seoInfo from "./from/seoInfo.vue";
import collection from "./from/collection.vue";
import { scrollType, modeProp } from "@/type.d";
import baseModal from "@/components/modal/baseModal.vue";
import transfer from "./transfer/index.vue";
import { useRoute, useRouter } from "vue-router";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import { Modal, message } from "ant-design-vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
//type or interface
type configDataType = {
  total: number;
  size: number;
  records: any[];
};

//data
let channelPermDto = reactive<dataSourceType>({});
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
const channelName = ref<string>(""); //当前栏目
const modelId = ref<string>("");
const basicDefult = ref<string>("");
const extDefault = ref<string>("");
const seoDefault = ref<string>("");
const basic = ref<any>(null);
const ext = ref<any>(null);
const seo = ref<any>(null);
const collect = ref<any>(null);
const rule = {
  required: true, //是否必填
  //validator: checkNameForm,//校验函数
  trigger: ["blur"], //校验事件
  msg1: "1111", //校验提示文案
  msg2: "访问路径不能重复!", //校验提示文案
  api: "fetchOssNameUnique", //需要用到校验的api
  key: "siteDomain",
  params: {}, //校验传参
};
const isShowCollect = ref<boolean>(false);
let isVisibleObj = reactive({ isVisible: false }); //判断是否展示添加弹窗
const buttons = ref<dataSourceType[]>([
  {
    text: "确定",
    "html-type": "submit",
    keepAlive: true,
  },
]); //模态框button按钮个数和文案修改
const selectSite = ref<number | string>("");
const contentSiteList = ref<dataSourceType[]>([
  { value: 1, label: "本站点" },
  { value: 2, label: "全部站点" },
]);

//内容模板列表
const contentModelList = ref<dataSourceType[]>([]);
const mobileTplList = ref<dataSourceType[]>([]);
const pcTplList = ref<dataSourceType[]>([]);
const rowSelectedKey = ref<dataSourceType[]>([]);
const contentModelListSelect = ref<dataSourceType[]>([]);
let addModelSelection = ref<(string | number)[]>([]);
const modelName = ref<string>("");
const isBasicSetting = ref<boolean>(true);
const isCancel = ref<boolean>(true);
const isShowCreateModel = ref<boolean>(true);
let detailData = reactive<dataSourceType>({});
//基础设置
const basicFormState = ref<dataSourceType[]>([]);
//扩展设置
const extFormState = ref<dataSourceType[]>([]);
//seo设置
const seoFormState = ref<dataSourceType[]>([]);
//采集设置
let collectionState = reactive<dataSourceType>({});
const addModelBaseTables = ref<any>(null); // 新建模型basetable的ref
let record = reactive<detailDataItemType>({});
const selectSiteData = ref<string | number>(""); // 下拉选择树已选中（当前值值）
const tranfer_isVisible = ref<Boolean | any>(false);
const route: any = useRoute();
const router: any = useRouter();
const deleteTips = ref<String>("是否将此栏目移入回收站？"); //站点删除提示语
const editActiveKey = ref<string | number>("1");
const modalProps: modeProp = reactive({
  //添加成员modal选项
  width: "L",
  title: "新增模型",
});

//computed

addModelSelection = computed(() => {
  return (
    (!isCancel.value &&
      addModelBaseTables.value &&
      addModelBaseTables.value.selectedRowKeys) ||
    contentModelListSelect.value
  );
});

//methods

// const selectTplChange = (record: any) => {
//   //获取添加上级组织id
//   console.log(record, 11111);
//   fetchChannelTplList(record.id);
// };
const onFocus = (id: number, type: any = null) => {
  pcTplList.value = []
  fetchChannelTplList(id, type);
};

// watch
watch(() => addModelBaseTables.value?.selectedRowKeys, (newVal: any, oldVal: any) => {
  if(newVal.length > 0){
    console.log(newVal,'newVal');
    onFocus(newVal[newVal.length - 1])
  }
});

const buttonMessage = () => {
  isVisibleObj.isVisible = false;
  contentModelListSelect.value = addModelBaseTables.value.selectedRowKeys;

  isCancel.value = false;
};
const handleCancle = () => {
  addModelBaseTables.value.selectedRowKeys = contentModelListSelect.value;
  isCancel.value = true;
  isVisibleObj.isVisible = false;
};

const rebackConfig = async () => {
  const data = await request.fetchChannelRecoverSiteConfig({
    channelId: route.query.channelId,
  });
};

//获取栏目详情
const getDetail = async () => {
  const data: {} = {
    id: route.query.channelId,
  };
  detailData = await request.fetchChannelDetail(data);

  nextTick(() => {

    const basic = detailData.basic && JSON.parse(detailData.basic);
    const ext = detailData.ext && JSON.parse(detailData.ext);
    const seo = detailData.seo && JSON.parse(detailData.seo);
    contentModelListSelect.value = detailData.contentModelTplDtoList || [];
    if (!contentModelListSelect.value.length) {
      fetchChannelContentModelTplList(1);
    } else {
      fetchChannelContentModelTplList();
    }
    const settingsInfo = detailData.enableJson ? JSON.parse(detailData.enableJson) : {};
    basicFormState.value = settingsInfo.formListBase || [];
    extFormState.value = settingsInfo.formListExtend || [];
    seoFormState.value = settingsInfo.formListSeo || [];

    basicFormState.value.length &&
      basicFormState.value.forEach((item: dataSourceType) => {
        item.value = basic[item.param] || item.value;
      });
    extFormState.value.length &&
      extFormState.value.forEach((item: dataSourceType) => {
        item.value = ext[item.param] || item.value;
      });
    seoFormState.value.length &&
      seoFormState.value.forEach((item: dataSourceType) => {
        item.value = seo[item.param] || item.value;
      });
    isShowCollect.value = detailData.leafNodeFlag;
    collectionState = {};
    if (detailData.rules) {
      const isNOdata = Object.values(detailData.rules).every((item: any) => item === null);
      collectionState = isNOdata ? {} : detailData.rules;
    }

    channelName.value = detailData.channelName;
    modelName.value = detailData.modelName;
    channelPermDto = detailData.channelPermDto;
    modelId.value = detailData.id;
    basicDefult.value = detailData.basic;
    extDefault.value = detailData.ext;
    seoDefault.value = detailData.seo;
  })
};

//获取内容模型列表
const fetchChannelContentModelTplList = async (type?: number) => {
  const list: dataSourceType[] = await request.fetchChannelContentModelTplList({
    channelId: route.query.channelId,
  });
  if (!list.length && type === 1) {
    Modal.confirm(
      Object.assign({}, msgModal.confirm, {
        title: "内容模型未关联模板，请前往内容模板关联模型",
        content: "",
        icon: createVNode("i", {
          class: "iconfont icon-warn warning_ICON",
        }),
        okText: "前往创建",
        cancelButtonProps: { style: { display: "none" } } as any,
        onOk: () => {
          router.push({
            path: "/config/templateManagement",
          });
        },
      })
    );
  }

  list.length &&
    list.forEach((item: any) => {
      item.id = item.modelId;
      item.name = item.modalName;
      item.tplPc = item.tplPc;
      if (item.selected) {
        rowSelectedKey.value.push(item.modelId);
      }
    });
  contentModelList.value = list || [];
  const ids = contentModelList.value.map((item: any) => {
    return item.modelId;
  });
  fetchChannelModelTplList(ids);
};
//获取内容模型列表
const fetchChannelModelTplList = async (ids: number[]) => {
  const list =
    (await request.fetchChannelModelTplList({ modelIdList: ids, siteId: "" })) || [];

};
//根据模型ID获取关联的模板列表
const fetchChannelTplList = async (id: number, type: any = null) => {
  const list =
    (await request.fetchChannelTplList({ modelIdList: [id], siteId: "" })) || []
  list.data[id]?.pcTplList && list.data[id].pcTplList.length && list.data[id].pcTplList.map((item: string) => {
    let obj = { label: item, value: item }
    pcTplList.value.push(obj)
    if(!type) {
      contentModelList.value.forEach((item2: any) => {
      if(id == item2.id) {
        if(!item2.tplPc) {
          item2.tplPc = item
        }
      }
    })
    }
  })
};

const mergeRecords = async () => {
  tranfer_isVisible.value = true;
};
// 删除提示文案变更
const deleteRecords = async () => {
  // 调接口删除敏感词
  if (record.children instanceof Array) {
    deleteTips.value = "是否将此栏目移入回收站？";
  }
};
//确认删除站点
const confirmDelete = async () => {
  // 更改站点开启或关闭状态
  if (record.children instanceof Array) {
    return;
  }
  let params = {
    id: route.query.channelId,
  };
  await request
    .fetchChannelRecycled(params)
    .then((res: detailDataItemType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        router.push({
          path: "/colunm/index",
          name: "栏目管理",
        });
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

//切换基础设置以及采集设置
const changeBasic = (bool: boolean) => {
  isBasicSetting.value = bool;
};

//保存数据
const saveData = async () => {
  let formRef: any = null;
  if (basic.value && editActiveKey.value == 1) {
    formRef = basic.value.basicFormRef;
  } else if (editActiveKey.value == 2) {
    formRef = ext.value.extFormRef;
  } else if (editActiveKey.value == 3) {
    formRef = seo.value.seoFormRef;
  } else {
    formRef = collect.value.collectionForm;
  }
  let rules =
    isShowCollect.value || collectionState
      ? collect.value
        ? collect.value.formParams
        : collectionState
      : null;
  let basicParam = basic.value
    ? basic.value.basicFormParam
    : { basic: basicDefult.value };
  let extParam = ext.value ? ext.value.extFormParam : { ext: extDefault.value };
  let seoParam = seo.value ? seo.value.seoFormParam : { seo: seoDefault.value };
  let params = {};
  params = isBasicSetting.value
    ? {
      id: route.query.channelId,
      ...basicParam,
      ...extParam,
      ...seoParam,
    }
    : {
      id: route.query.channelId,
      rules,
    };
  if (isBasicSetting.value) {
    basic.value.basicFormRef.validate().then(() => {
      ext.value.extFormRef.validate().then(() => {
        seo.value.seoFormRef.validate().then(() => {
          request["fetchChannelUpdateConfig"](
            params
          )
            .then((res: any) => {
              if (res.code == "00000 00000") {
                router.push('/colunm/index');
                // getDetail(); // 重新调取详情接口;
                // fetchChannelContentModelTplList();
                message.success(res.message);
              } else {
                message.error(res.message);
              }
            })
            .catch((err: any) => {
              throw new Error(err);
            });
        }).catch((err: any) => {
          console.log(err, 13333333)
          editActiveKey.value = '3'
        })
      }).catch((err: any) => {
        editActiveKey.value = '2'
      })
    }).catch((err: any) => {
      editActiveKey.value = '1'
    })
  } else {
    collect.value.collectionForm.validate().then(() => {
      request["fetchChannelUpdateRules"](
        params
      )
        .then((res: any) => {
          if (res.code == "00000 00000") {
            router.push('/colunm/index');
            // getDetail(); // 重新调取详情接口;
            // fetchChannelContentModelTplList();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    })
  }
};
//栏目预览
const goToChannelPreview = () => {
  window.open(detailData.previewAddress)
}
const handleOk = (e: MouseEvent) => {
  getDetail();
};
//onMounted
onMounted(() => {
  getDetail();
  useFixeWidth();
});
</script>

<style lang="less" scoped>
.colunmDetail {
  background-color: #fff;
  width: 100%;
  height: calc(100% - 136px);
  padding-bottom: 56px;

  .colunmDetail-header {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    padding: 0 24px;

    .tree-select {
      display: flex;
      width: auto;
      align-items: center;
      margin-right: 16px;

      span {
        font-size: 14px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
        margin-right: 12px;
      }

      .AtreeSelect {
        width: 144px;
        min-width: 144px;
      }

      .AtreeSelect.ant-select-open {
        width: 300px;
      }
    }

    .createStaticPage {
      margin-right: 8px;
    }

    .previewSite {
      margin-right: 8px;
    }

    .deleteSite {
      margin-right: 8px;
    }
  }

  .basic-item {
    margin-top: 24px;
    margin-left: 86px;
  }


}
.tpllPc {
        display: flex;
        align-items: center;
        .title {
          margin-right: 5px;
        }
        .tips {
          display: inline-block;
          margin-left: 5px;
            width: 125px;
            font-size: 12px;
            color:rgba(0,0,0,.4);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
      }

::v-deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
  text-align: left;
}

.modal-select {
  width: 204px;
}

.rebackSite {
  margin-bottom: 16px;
}

.searchContent {
  margin-left: 16px;

  ::v-deep(.ant-input-affix-wrapper) {
    height: 32px;
  }
}

.colletion {
  height: calc(100% - 24px);
  overflow: auto;
}

.table-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-bottom: 24px;
}

.ant-table-thead .ant-table-cell:nth-last-of-type(1) {
  text-align: left;
}
</style>
<style lang="less">
.colunmDetail {
  .ant-form-item-control-input {

    .ant-select,
    .ant-input-affix-wrapper {
      width: 304px;
    }

    .editor-container {
      width: 100%;
      max-width: 900px;
    }
  }
}


.AtreeSelect .ant-select-selector {
  width: 144px;
  transition: width 0.1s cubic-bezier(0.075, 0.82, 0.165, 1);
}

.AtreeSelect.ant-select-open .ant-select-selector {
  width: 300px;
}

.colunmDetail .AtreeSelect .ant-select-selector .ant-select-selection-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.columnInfoDetail .ant-tabs-tab {
  padding: 0px 0 8px;
}

.colunmDetail .table-bottom_fiexd {
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  background: #fff;
}

.colunmDetail-modal .ant-modal-confirm-content {
  display: none;
}

.columnInfoDetail {
  padding-left: 24px;
  height: calc(100% - 102px);
  overflow: hidden;

  .ant-tabs.ant-tabs-top {
    height: 32px;
    overflow: hidden;
  }

  .columnSettings {
    height: calc(100% - 32px);
    overflow: auto;
  }
}

.now-colunm {
  margin-left: 24px;
  margin-bottom: 3px;
  font-size: 14px;

  span {
    color: black;
  }
}
</style>
